package com.wzdigit.wms.wms.service.basic;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.request.basic.*;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.client.response.basic.CarrierApiResponse;
import com.wzdigit.wms.basic.client.response.basic.CarrierResponse;
import com.wzdigit.wms.basic.client.response.basic.ImportCarrierErrorResponse;
import com.wzdigit.wms.basic.client.response.basic.ImportCarrierResponse;
import com.wzdigit.wms.basic.domain.basic.Carrier;
import com.wzdigit.wms.basic.enums.BaseIsEnabledEnum;
import com.wzdigit.wms.basic.mapper.core.basic.CarrierMapper;
import com.wzdigit.wms.common.utils.HttpExcel;
import com.wzdigit.wms.basic.util.HttpSessionUtil;
import com.wzdigit.wms.common.utils.ValidatorUtil;
import com.wzdigit.wms.common.entity.StatusCode;
import net.dreamlu.mica.core.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 承运人 服务类
 * @author yangdongjie
 * @LocationAttrService.java
 * @2021年1月4日上午11:16:31
 */
@Service
public class CarrierService {

	@Autowired
    private CarrierMapper carrierMapper;
	
	public List<CarrierApiResponse> list() {
		return carrierMapper.selectAllByStatus(BaseIsEnabledEnum.USE.code);
    }

	public CarrierResponse getCarrier(Integer carrierId) {
    	return carrierMapper.selectOneByCarrierId(carrierId);
    }
    
    @SuppressWarnings("rawtypes")
	public <T> PagerInfo<List<CarrierResponse>> searchCarrier(SearchCarrierRequest dto) {
    	Page<T> page = PageHelper.offsetPage(dto.getSkipCount(), dto.getMaxResultCount());
        PagerInfo<List<CarrierResponse>> pagerInfo = new PagerInfo<List<CarrierResponse>>();
        List<CarrierResponse> list = carrierMapper.selectAll(dto);
        pagerInfo.setItems(list);
        pagerInfo.setTotalCount(page.getTotal());
		return pagerInfo;
    }
    
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public CarrierResponse createCarrier(CreateCarrierRequest dto,
    		HttpServletRequest servletRequest) {
    	String loginName = HttpSessionUtil.getLoginName(servletRequest);
    	Carrier carrier = carrierMapper.selectOneByCarrierCode(dto.getCarrierCode());
    	if(carrier != null) {
    		// 编码已存在
    		Shift.fatal(StatusCode.CODE_DATA_EXIST);
    	}
    	carrier = new Carrier();
    	BeanUtil.copyNonNull(dto, carrier);
    	carrier.setCreateUser(loginName);
    	carrier.setCreateTime(new Date());
    	carrierMapper.insert(carrier);
    	
    	CarrierResponse response = new CarrierResponse();
    	BeanUtil.copyNonNull(carrier, response);
		return response;
    }
    
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public CarrierResponse updateCarrier(UpdateCarrierRequest dto,
    		HttpServletRequest servletRequest) {
    	String loginName = HttpSessionUtil.getLoginName(servletRequest);
    	Carrier carrier = carrierMapper.selectOneByCarrierCode(dto.getCarrierCode());
    	if(carrier != null) {
    		if (dto.getCarrierId().intValue() != carrier.getCarrierId().intValue()) {
    			// 编码已存在
    			Shift.fatal(StatusCode.CODE_DATA_EXIST);
			}
    	}
    	carrier = carrierMapper.selectByPrimaryKey(dto.getCarrierId());
    	BeanUtil.copy(dto, carrier);
    	carrier.setModifyUser(loginName);
    	carrier.setModifyTime(new Date());
    	carrierMapper.updateById(carrier);
    	
    	CarrierResponse response = new CarrierResponse();
    	BeanUtil.copy(carrier, response);
		return response;
    }
    
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public <T> Result<T> updateStatus(UpdateStatusCarrierRequest dto,
    		HttpServletRequest servletRequest) {
    	String loginName = HttpSessionUtil.getLoginName(servletRequest);
    	Carrier carrier = carrierMapper.selectByPrimaryKey(dto.getCarrierId());
    	carrier.setStatus(dto.getStatus());
    	carrier.setModifyUser(loginName);
    	carrier.setModifyTime(new Date());
    	carrierMapper.updateStatus(carrier);
		return new Result<>();
    }
    
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public ImportCarrierResponse importCarrier(
			MultipartFile file, 
			HttpServletRequest servletRequest, 
			HttpServletResponse servletResponse) throws Exception {
    	
    	String loginName = HttpSessionUtil.getLoginName(servletRequest);
    	List<ImportCarrierRequest> excel = null;
		try {
			InputStream inputStream = file.getInputStream();
			String[] properties = { "carrierCode", "carrierName", "carrierAddress", 
					"carrierContact", "carrierTel", "carrierEmail", "carrierFax" };
			excel = HttpExcel.importExcel(inputStream, ImportCarrierRequest.class, properties);
		} catch (Exception e) {
			// 模板错误，请确认
			e.printStackTrace();
			Shift.fatal(StatusCode.IMPORT_DATA_ERROR);
		}
		
		if (excel == null || excel.size() == 0) {
			// 该模板数据为空
			Shift.fatal(StatusCode.IMPORT_DATA_NULL);
		}

		// 失败、成功条数
		int fail = excel.size(), sucess = 0;
		// 失败记录集合
		List<ImportCarrierErrorResponse> errors = new ArrayList<>();

		for (ImportCarrierRequest dto : excel) {
			boolean flag = true;

			// 1：检验参数
			for (String message : ValidatorUtil.validatorMessages(dto)) {
				ImportCarrierErrorResponse error = new ImportCarrierErrorResponse();
				BeanUtil.copyNonNull(dto, error);

				StringBuilder errorDec = new StringBuilder("【第");
				errorDec.append(dto.getRow()).append("行】").append(message);
				error.setRowMessage(errorDec.toString());

				errors.add(error);
				flag = false;
			}

			if (flag) {
				Carrier carrier = carrierMapper.selectOneByCarrierCode(dto.getCarrierCode());
				// 编码已存在
				if (carrier != null) {
					ImportCarrierErrorResponse error = new ImportCarrierErrorResponse();
					BeanUtil.copyNonNull(dto, error);

					StringBuilder errorDec = new StringBuilder("【第");
					errorDec.append(dto.getRow()).append("行】").append(StatusCode.CODE_DATA_EXIST.message());
					error.setRowMessage(errorDec.toString());

					errors.add(error);
					flag = false;
				}
			}

			if (flag) {
				Carrier carrier = new Carrier();
				BeanUtil.copyNonNull(dto, carrier);
				carrier.setCreateUser(loginName);
				carrier.setCreateTime(new Date());
				carrier.setStatus(BaseIsEnabledEnum.USE.code);
				carrierMapper.insert(carrier);
				--fail;
				++sucess;
			}
		}
		ImportCarrierResponse response = new ImportCarrierResponse();
		response.setFailureCount(fail);
		response.setSucceessCount(sucess);
		response.setItems(errors);
		return response;
	}
}
